import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import { Drawer } from 'antd';
import { useResizableDrawer, getDrawerSize, setDrawerSize } from '../../hooks/useResizableDrawer';

const StyledDrawer = styled(Drawer)`
  transition: width, height 0s ease;
`;

const ResizeBar = styled.div`
  position: absolute;
  background-color: rgba(0, 0, 0, 0.1);
  z-index: 1;

  ${props => props.direction === 'left' && `
    cursor: col-resize;
    width: 4px;
    height: 100%;
    top: 0;
    right: 0;
  `}

  ${props => props.direction === 'right' && `
    cursor: col-resize;
    width: 4px;
    height: 100%;
    top: 0;
    left: 0;
  `}

  ${props => props.direction === 'bottom' && `
    cursor: row-resize;
    height: 4px;
    width: 100%;
    left: 0;
    bottom: 0;
  `}

  ${props => props.direction === 'top' && `
    cursor: row-resize;
    height: 4px;
    width: 100%;
    left: 0;
    top: 0;
  `}
`;

const ResizableDrawer = ({
  drawerKey,
  size = 560,
  title = '',
  open = false,
  direction = 'right',
  onClose,
  children,
}) => {
  const [drawerSize, setDrawerSizeState] = useState(getDrawerSize(drawerKey, size));
  const [visible, setVisible] = useState(open);

  useEffect(() => {
    setVisible(open);
  }, [open]);

  useEffect(() => {
    if (drawerKey) {
      setDrawerSize(drawerKey, drawerSize);
    }
  }, [drawerKey, drawerSize]);

  const {
    resizeBarRef,
    onMouseDown,
    onClosed,
    drawerClassName,
  } = useResizableDrawer({
    drawerKey,
    direction,
    drawerSize,
    setDrawerSize: setDrawerSizeState,
    onClose,
  });

  return (
    <StyledDrawer
      height={'100%'}
      open={visible}
      className={drawerClassName}
      width={drawerSize}
      title={title}
      placement={direction}
      onClose={onClosed}
    >
      <ResizeBar
        ref={resizeBarRef}
        direction={direction}
        onMouseDown={onMouseDown}
      />
      {children}
    </StyledDrawer>
  );
};

export default ResizableDrawer; 